#include "HomeWnd.h"

#include <QTimer>
#include <QDateTime>

#include "AppModel.h"

HomeWnd::HomeWnd(QWidget *parent)
	: QWidget(parent)
{
    setAttribute(Qt::WA_StyledBackground);
	ui.setupUi(this);
	this->setFixedSize(this->width(), this->height());

	// init
    auto pix = QPixmap("./cache/logo.png").scaledToHeight(ui.lb_logo->height());
    ui.lb_logo->setPixmap(pix);
    ui.lb_logo->installEventFilter(this);
    ui.wnd_numpad->enableKeyOK(true);
    ui.wnd_content->setCurrentIndex(0);
    ui.edt_card_no->setProperty("noinput", true);

    // 自动更新时间
	auto timer = new QTimer(this);
	timer->start(1000);
	connect(timer, &QTimer::timeout, this, [&]() {
        ui.lb_time->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
	});
    connect(&timer_, &QTimer::timeout, this, [&]() {
        ui.wnd_content->setCurrentIndex(0);
    });

	// connect
	connect(ui.btn_deposit, &QAbstractButton::clicked, this, &HomeWnd::depositEvent);
    connect(ui.btn_fetch, &QAbstractButton::clicked, this, &HomeWnd::fetchEvent);

    connect(ui.wnd_numpad, &CCustomNumpad::key, this, &HomeWnd::event_numpad_key_clicked);
    connect(ui.wnd_numpad, &CCustomNumpad::ok, this, &HomeWnd::event_numpad_ok_clicked);
    connect(ui.wnd_numpad, &CCustomNumpad::del, this, &HomeWnd::event_numpad_del_clicked);
}

void HomeWnd::SetCabinetName(const QString & name)
{
    ui.lb_cabinet_name->setText(tr("No.: %1").arg(CabinetID().c_str()));
    ui.lb_title->setText(name);
}

bool HomeWnd::eventFilter(QObject * watched, QEvent * event)
{
    if (qobject_cast<QLabel*>(watched) == ui.lb_logo)
	{
		if (event->type() == QEvent::MouseButtonDblClick)
        {
            ui.wnd_content->setCurrentIndex(1);
            ui.edt_card_no->clear();
            ui.edt_card_no->setFocus();
            timer_.stop();
            timer_.start(15 * 1000);
		}
	}

	return QWidget::eventFilter(watched, event);
}


void HomeWnd::on_edt_card_no_returnPressed()
{
    QString cardno = ui.edt_card_no->text();
    ui.edt_card_no->clear();
	emit cardLogin(cardno);

    ui.wnd_content->setCurrentIndex(0);
}

void HomeWnd::on_btnd_back_clicked()
{
    ui.wnd_content->setCurrentIndex(0);
}

void HomeWnd::event_numpad_key_clicked(const QString &key)
{
    QLineEdit* edt = qobject_cast<QLineEdit*>(this->focusWidget());
    if (edt == nullptr)
    {
        return;
    }

    edt->setText(edt->text() + key);
}

void HomeWnd::event_numpad_del_clicked()
{
    ui.edt_card_no->clear();
    ui.edt_card_no->setFocus();
}

void HomeWnd::event_numpad_ok_clicked()
{
    on_edt_card_no_returnPressed();
}

